package com.kefu.z.intermediator.system;

import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONObject;
import com.kefu.z.intermediator.MethodType;
import com.kefu.z.intermediator.SocketRequest;
/**
 * websocket处理类
 * @author Halo
 *
 */
public class SystemWebSocketHandler extends TextWebSocketHandler{
	
	/**
	 * js调用websocket.send时候，会调用该方法
	 */
	protected void handleTextMessage(WebSocketSession session,  
            TextMessage message) throws Exception {  
        System.out.println("handleTextMessage");
		JSONObject json=JSONObject.parseObject(message.getPayload());
		SocketRequest sr=json.toJavaObject(SocketRequest.class);
		switch (sr.getMethod()) {
		case MethodType.TOGGLE_USER:
			//切换管理账户
			//触发向客户端推送事件
			break;
		default:
			break;
		}
		//TODO
		TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
        session.sendMessage(returnMessage);
    }
	/**
	 * 支持部分信息
	 */
	public boolean supportsPartialMessages() {
		return true;
	}
	/**
	 * 在连接建立
	 */
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println("afterConnectionEstablished");
	}

	/**
	 * 处理消息
	 */
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		if (message instanceof TextMessage) {
			handleTextMessage(session, (TextMessage) message);
		}
		else if (message instanceof BinaryMessage) {
			handleBinaryMessage(session, (BinaryMessage) message);
		}
		else if (message instanceof PongMessage) {
			handlePongMessage(session, (PongMessage) message);
		}
		else {
			throw new IllegalStateException("Unexpected WebSocket message type: " + message);
		}
	}
	/**
	 * 
	 */
	protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
		System.out.println("handlePongMessage");
	}

	/**
	 * 处理传输错误
	 */
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		System.out.println("handleTransportError");
	}
	/**
	 * 连接关闭后
	 */
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		System.out.println("afterConnectionClosed");
	}
}
